package com.mtw.bbs.common.web.feign;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.mtw.bbs.common.core.exception.BusinessException;
import com.mtw.bbs.common.core.vo.Result;
import feign.Response;
import feign.codec.Decoder;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import java.io.Reader;
import java.lang.reflect.Type;
import java.nio.charset.Charset;

/**
 * 全局feign响应拆包
 */
@Slf4j
//@Configuration
@RequiredArgsConstructor
public class FeignUnwrapDecoder implements Decoder {

    private final ObjectMapper objectMapper;

    @SneakyThrows
    @Override
    public Object decode(Response response, Type type) {
        Reader reader = response.body().asReader(Charset.defaultCharset());
        Result<?> result = objectMapper.readValue(reader, Result.class);
        // 根据 code 判断操作是否成功
        if (result.isSuccess()) {
            Object data = result.getData();
            JavaType javaType = TypeFactory.defaultInstance().constructType(type);
            return objectMapper.convertValue(data, javaType);
        }
        // 若不成功，抛出业务异常，注意此处的异常会在 DecodeException 中被捕获
        throw new BusinessException(result.getCode(), result.getMesg());
    }
}
